package com.shopcart.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.shopcart.entity.Customer;

public class AuthorizationFilter implements Filter {

	public AuthorizationFilter() {

	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * Check the authorization in every page the customer visits Do not
	 * check authorization in the login and logout pages
	 * 
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpSession session = ((HttpServletRequest) request)
				.getSession();
		Customer c = (Customer) session.getAttribute("customer");
		if (c == null)
			returnError(request, response,
					"You are not authorized to see the page");
		// pass the request along the filter chain
		else {
			if (((HttpServletRequest) request).getRequestURI()
					.equals("/ShoppingCartWeb/admin.jsp") &&
					!c.getCustomerType().equals("admin")){
				RequestDispatcher rd = request
						.getRequestDispatcher("home.jsp");
				rd.forward(request, response);
				return;
			}

			chain.doFilter(request, response);
		}
	}

	private void returnError(ServletRequest request,
			ServletResponse response, String errorString)
			throws ServletException, IOException {
		RequestDispatcher rd = request
				.getRequestDispatcher("login.jsp");
		rd.forward(request, response);
		return;
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
